<template>
  <div class="page-container">
    <div class="in-container">
      <AppSearchForm @submit="search()" @reset="reset()">
        <el-form-item>
          <el-input
            v-model="state.query.name"
            clearable
            placeholder="输入通知人、收货人、发货人"
            style="width: 200px"
          />
        </el-form-item>
      </AppSearchForm>
      <div class="nav-tab">
        <el-button @click="state.dialogData.show = true" type="primary">
          新增
        </el-button>
        <el-button @click="deleteSelectData" type="danger"> 删除 </el-button>
      </div>
      <AppPageTable
        stripe
        :data="state.tableData.data"
        @change="getTableData()"
        :autostyle="'height:calc(100% - 64px) ;'"
        :option="state.tableData.option"
      >
        <el-table-column
          show-overflow-tooltip
          type="selection"
          width="40"
          fixed="left"
        />
        <el-table-column prop="type" width="140" label="类别" />
        <el-table-column prop="title" width="200" label="名称" show-overflow-tooltip />
        <el-table-column prop="code" width="140" label="代码" />
        
        <el-table-column prop="address" width="200" label="地址" show-overflow-tooltip />
        <el-table-column prop="telephone" width="140" label="电话" />
        <el-table-column prop="fax" width="140" label="传真" />
        <el-table-column prop="email" width="140" label="EMAIL" />
        <el-table-column prop="wholeText" width="200" label="名址全文" />

        <el-table-column prop="country" width="200" label="国家" />
        <el-table-column prop="countryCode" width="200" label="国家代码" />
        <el-table-column prop="city" width="200" label="城市" />

        <el-table-column label="操作" width="140" fixed="right">
          <template #default="scope">
            <el-button @click="update(scope.row)" type="primary"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除本条数据吗？"
              @confirm="deleteData(scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </AppPageTable>
      <el-dialog
        v-model="state.dialogData.show"
        title="新增收发货人"
        width="40%"
      >
        <el-form
          :model="state.formData"
          :rules="state.formRules"
          ref="form"
          label-width="100px"
          label-suffix="："
        >
          <el-form-item label="类型" prop="type">
            <el-select v-model="state.formData.type" placeholder="请选择类型">
              <el-option label="收货人" value="收货人"></el-option>
              <el-option label="发货人" value="发货人"></el-option>
              <el-option label="通知人" value="通知人"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="代码" prop="code">
            <el-input v-model="state.formData.code" placeholder="请输入代码"></el-input>
          </el-form-item>
          <el-form-item label="名称" prop="title">
            <el-input v-model="state.formData.title" placeholder="请输入名称"></el-input>
          </el-form-item>

          <el-form-item label="地址" prop="address">
            <el-input v-model="state.formData.address" placeholder="请输入地址"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="telephone">
            <el-input v-model="state.formData.telephone" placeholder="请输入电话"></el-input>
          </el-form-item>
          <el-form-item label="传真" prop="fax">
            <el-input v-model="state.formData.fax" placeholder="请输入地址"></el-input>
          </el-form-item>
          <el-form-item label="email" prop="email">
            <el-input v-model="state.formData.email" placeholder="请输入email"></el-input>
          </el-form-item>
          <el-form-item label="名址全文" prop="wholeText">
            <el-input v-model="state.formData.wholeText" placeholder="请输入名址全文"></el-input>
          </el-form-item>

          <el-form-item label="国家" prop="country">
            <el-select 
              v-model="state.formData.country"
              filterable
              remote
              placeholder="输入币别搜索"
              :remote-method="countrySelect"
              :loading="state.selectLoading"
              @change="countryChange"
            >
            <el-option
              v-for="item in state.countryOption"
              :key="item.id"
              :label="item.countryCh"
              :value="item.countryCh"
            />
            </el-select>
          </el-form-item>

          <el-form-item label="城市" prop="city">
            <el-select 
              v-model="state.formData.city"
              filterable
              placeholder="输入币别搜索"
            >
            <el-option
              v-for="item in state.cityOption"
              :key="item.id"
              :label="item.nameCh"
              :value="item.nameCh"
            />
            </el-select>
          </el-form-item>
          
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel" link>取消</el-button>
            <el-button
              type="primary"
              @click="submit"
              :loading="state.dialogData.btnLoading"
            >
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  watch,
  computed,
  reactive,
  nextTick,
  defineEmits,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/public/request";

import AppSearchForm from "@/components/AppSearchForm.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";

const state = reactive({
  tableData: {
    data: [],
    option: useTableOption(),
  },
  dialogData: {
    show: false,
    btnLoading: false,
  },
  formData: {
    code: "",
    title: "",
    address: "",
    telephone: "",
    fax: "",
    country: "",
    zipCode: "",
    city: "",
    type: "",
    wholeText: "",
    countryCode: "",
    email: ""
  },
  formRules: {
    title: [{ required: true, message: "请输入抬头名称", trigger: "blur" }],
    type: [{ required: true, message: "请选择类型", trigger: "blur" }]
  },
  query: {
    name: "",
  },
  selectData: {
    options: [],
    loading: false,
  },
  countryOption: [],
  countryId: "",
  cityOption: []
});

const search = () => {
  state.tableData.option.page = 1;
  getTableData();
};
const reset = () => {
  state.tableData.option.page = 1;
  state.tableData.option.pageSize = 10;
  state.query.name = "";
  getTableData();
};
const getTableData = () => {
  state.tableData.option.loading = true;
  request
    .get("/api/csshipperconsignee/querypage", {
      KeyWords: state.query.name,
      PageIndex: state.tableData.option.page,
      PageSize: state.tableData.option.pageSize,
    })
    .then((res) => {
      state.tableData.data = res.content;
      state.tableData.option.total = res.totalElements;
    })
    .finally(() => {
      state.tableData.option.loading = false;
    });
};
const update = (data) => {
  state.formData = JSON.parse(JSON.stringify(data));
  state.selectData.options = [
    {
      id: data.entId,
      value: data.entId,
      label: data.entName,
    },
  ];
  state.dialogData.show = true;
};
const form = ref();
const submit = () => {
  let url = "";
  if (state.formData.id) {
    url = "/api/csshipperconsignee/update";
  } else {
    url = "/api/csshipperconsignee/create";
    state.formData.id = 0;
  }
  form.value.validate((valid) => {
    if (valid) {
      state.dialogData.btnLoading = true;
      request
        .post(url, state.formData)
        .then((res) => {
          if (res.status) {
            ElMessage.success(res.message);
            getTableData();
            state.dialogData.show = false;
          } else {
            ElMessage.error(res.message);
          }
        })
        .finally(() => (state.dialogData.btnLoading = false));
    }
  });
};
const cancel = () => {
  state.dialogData.show = false;
};
const deleteData = (data) => {
  request
    .post("/api/csshipperconsignee/delete", {
      idArray: [data.id],
    })
    .then((res) => {
      if (res.status) {
        ElMessage.success(res.message);
        getTableData();
      } else {
        ElMessage.error(res.message);
      }
    });
};
const countrySelect = (query) => {
  state.selectLoading = true;
  request
    .get("/api/cscountry/querypage", {
      KeyWords: query,
      PageIndex: 1,
      PageSize: 50,
    })
    .then((res) => {
      state.countryOption = res.content;
    })
    .finally(() => {
      state.selectLoading = false;
    });
};
const countryChange = async (data) => {
  state.formData.city = "";
  state.cityOption = [];

  if(!data){
    state.formData.country = "";
    state.formData.countryCode = "";
  }
  
  var arr = state.countryOption.filter(item => {
    return item.countryCh == data
  })[0];
  var id = arr.id;
  state.formData.countryCode = arr.countryCode;
  let res = await request.get('/api/cscistrict/query',{
    Id: id
  })
  state.cityOption = res.content;
}
/**
 * 多项删除业务
 */
const deleteSelectData = () => {
  let deleteSelectArray = [];
  state.tableData.option.selected.forEach((t) => deleteSelectArray.push(t.id));
  ElMessageBox.confirm("确定删除所选收发货人信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      request
        .post("/api/csshipperconsignee/delete", {
          idArray: deleteSelectArray,
        })
        .then((res) => {
          if (res.status) {
            ElMessage.success(res.message);
            getTableData();
          } else {
            ElMessage.error(res.message);
          }
        });
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};

watch(
  () => state.dialogData.show,
  (newVal) => {
    if (!newVal) {
      state.formData = {
        code: "",
        title: "",
        address: "",
        telephone: "",
        fax: "",
        country: "",
        zipCode: "",
        city: "",
        type: "",
        wholeText: "",
        countryCode: "",
        email: ""
      };
      nextTick(() => {
        form.value.resetFields();
      });
    }
  }
);

onMounted(() => {
  getTableData();
});
</script>

<style lang="scss" scoped>
.nav-tab {
  margin-bottom: 8px;
}
</style>
